package com.example.restatr.Atcivity.Hospital;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.restatr.Atcivity.Main.MainActivity;
import com.example.restatr.Atcivity.Hospital.Bean.HospitalCategoryBean;
import com.example.restatr.Atcivity.Hospital.Bean.HospitalPatientBean;
import com.example.restatr.R;
import com.example.restatr.Tools;
import com.google.android.material.button.MaterialButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class HospitalSetPatientAt extends AppCompatActivity {
    private Toolbar toolbar;
    private TextView barTitle;
    private EditText search;
    private EditText name;
    private RadioButton infoNan;
    private RadioButton infoNv;
    private EditText phoneNumber;
    private EditText idCard;
    private EditText address;
    private TextView date;
    private MaterialButton mileageCommit;
    private HospitalPatientBean.RowsBean data;
    private String sex = "";
    private TextView text1;
    private TextView text2;
    private TextView text3;
    private TextView text4;
    private TextView text5;
    private TextView text6;
    private List<HospitalCategoryBean.RowsBean> rowsBeans = new ArrayList<>();
    private int categoryId;
    private LinearLayout text4_LL;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hospital_set_patient_at);
        toolbar = findViewById(R.id.toolbar);
        barTitle = findViewById(R.id.bar_Title);
        search = findViewById(R.id.search);
        name = findViewById(R.id.name);
        infoNan = findViewById(R.id.info_nan);
        infoNv = findViewById(R.id.info_nv);
        phoneNumber = findViewById(R.id.phoneNumber);
        idCard = findViewById(R.id.idCard);
        address = findViewById(R.id.address);
        date = findViewById(R.id.date);
        mileageCommit = findViewById(R.id.mileageCommit);
        text4_LL = findViewById(R.id.text_4);
        text1 = findViewById(R.id.text1);
        text2 = findViewById(R.id.text2);
        text3 = findViewById(R.id.text3);
        text4 = findViewById(R.id.text4);
        text5 = findViewById(R.id.text5);
        text6 = findViewById(R.id.text6);
        Tools.SetBarTitle(toolbar, barTitle, getIntent().getStringExtra("intent"), search, this, false);
        if (getIntent().getStringExtra("intent") != null) {
            if (getIntent().getStringExtra("intent").equals("修改信息")) {
                data = new Gson().fromJson(getIntent().getStringExtra("data"), new TypeToken<HospitalPatientBean.RowsBean>() {
                }.getType());
                name.setText(data.getName());
                if (data.getSex().equals("0")) {
                    infoNan.setChecked(true);
                } else {
                    infoNv.setChecked(true);
                }
                phoneNumber.setText(data.getTel());
                idCard.setText(data.getCardId());
                address.setText(data.getAddress());
                date.setText(data.getBirthday());
                mileageCommit.setText("提交修改");
            } else if (getIntent().getStringExtra("intent").equals("预约")) {
                text1.setText("姓名：");
                text2.setText("门诊类型");
                infoNan.setText("普通诊");
                infoNv.setText("专家诊");
                text3.setText("科室名称：");
                text4_LL.setVisibility(View.GONE);
                idCard.setText("1");
                text5.setText("金额：");
                address.setInputType(InputType.TYPE_CLASS_NUMBER);
                text6.setText("预约时间：");
                phoneNumber.setFocusable(false);
                phoneNumber.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        GetCategory();
                    }
                });
            }

        }

    }

    //生成预约单
    private void PostReservation() {
        new Thread(() -> {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("categoryId", categoryId);
                jsonObject.put("money", address.getText().toString());
                jsonObject.put("patientName", name.getText().toString());
                jsonObject.put("reserveTime", date.getText().toString());
                jsonObject.put("type", GetRadioCheck());
                String post = Tools.Post("/prod-api/api/hospital", MainActivity.sp.getString("token", ""), jsonObject.toString());
                JxJSON(post);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).start();
    }

    //获取门诊类型id
    private String GetRadioCheck() {
        if (infoNan.isChecked()) {
            return "1";
        } else {
            return "2";
        }
    }

    //查询专家诊与普通诊的科室分类
    private void GetCategory() {
        rowsBeans.clear();
        new Thread(() -> {
            String get = Tools.Get("/prod-api/api/hospital/category/list?type=" + GetRadioCheck(), "");
            HospitalCategoryBean hospitalCategoryBean = new Gson().fromJson(get, HospitalCategoryBean.class);
            rowsBeans.addAll(hospitalCategoryBean.getRows());
            runOnUiThread(() -> {
                if (rowsBeans.size() > 0) {
                    String[] items = new String[rowsBeans.size()];
                    for (int i = 0; i < rowsBeans.size(); i++) {
                        items[i] = rowsBeans.get(i).getCategoryName();
                    }
                    new AlertDialog.Builder(this)
                            .setItems(items, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    phoneNumber.setText(rowsBeans.get(which).getCategoryName());
                                    categoryId = rowsBeans.get(which).getId();
                                }
                            }).create().show();
                }
            });
        }).start();
    }

    //新增就诊信息
    private void PostPatient(HospitalPatientBean.RowsBean rowsBean) {
        new Thread(() -> {
            String post = Tools.Post("/prod-api/api/hospital/patient", MainActivity.sp.getString("token", ""), new Gson().toJson(rowsBean));
            JxJSON(post);
        }).start();
    }

    //修改就诊信息
    private void PutPatient(HospitalPatientBean.RowsBean rowsBean) {
        new Thread(() -> {
            String post = Tools.Put("/prod-api/api/hospital/patient", MainActivity.sp.getString("token", ""), new Gson().toJson(rowsBean));
            JxJSON(post);
        }).start();
    }

    //解析
    private void JxJSON(String object) {
        try {
            JSONObject jx = new JSONObject(object);
            String msg = jx.getString("msg");
            int code = jx.getInt("code");
            runOnUiThread(() -> {
                Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                if (code == 200) {
                    finish();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //获取性别
    private void GetSex() {
        if (infoNan.isChecked()) {
            sex = "0";
        } else if (infoNv.isChecked()) {
            sex = "1";
        }
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.date:
                View inflate = getLayoutInflater().inflate(R.layout.date_dailog_item, null);
                DatePicker datePicker = inflate.findViewById(R.id.date);
                TimePicker timePicker = inflate.findViewById(R.id.time);
                Button btn=inflate.findViewById(R.id.btn);
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setView(inflate).create();
                AlertDialog show = builder.show();
                datePicker.setOnDateChangedListener(new DatePicker.OnDateChangedListener() {
                    @Override
                    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        monthOfYear+=1;
                        if (getIntent().getStringExtra("intent").equals("预约")) {
                            date.setText(year + "-" + monthOfYear + "-" + dayOfMonth);
                            datePicker.setVisibility(View.GONE);
                            timePicker.setVisibility(View.VISIBLE);
                            btn.setVisibility(View.VISIBLE);
                        } else {
                            date.setText(year + "-" + monthOfYear + "-" + dayOfMonth);
                            show.dismiss();
                        }

                    }
                });
                btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        date.setText(date.getText() + " " + timePicker.getHour() + ":" + timePicker.getMinute());
                        show.dismiss();
                    }
                });
                break;
            case R.id.mileageCommit:
                GetSex();
                HospitalPatientBean.RowsBean rowsBean;
                if (Tools.isEmptyText(name) && Tools.isEmptyText(idCard) && Tools.isEmptyText(phoneNumber) &&
                        Tools.isEmptyText(date) && Tools.isEmptyText(address)) {
                    if (mileageCommit.getText().equals("提交修改")) {
                        //修改就诊人信息
                        rowsBean = new HospitalPatientBean.RowsBean(data.getId(), name.getText().toString(), idCard.getText().toString()
                                , phoneNumber.getText().toString(), sex, date.getText().toString(), address.getText().toString());
                        PutPatient(rowsBean);
                    } else if (getIntent().getStringExtra("intent").equals("预约")) {
                        //生成预约单
                        PostReservation();
                    } else {
                        //提交就诊人信息
                        rowsBean = new HospitalPatientBean.RowsBean(name.getText().toString(), idCard.getText().toString()
                                , phoneNumber.getText().toString(), sex, date.getText().toString(), address.getText().toString());
                        PostPatient(rowsBean);
                    }
                } else {
                    Toast.makeText(this, "不能为空！", Toast.LENGTH_SHORT).show();
                }

                break;
        }
    }

}